<?php

namespace App\Exports;

use App\Models\Airdrop;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;

class AirdropsExport implements FromQuery, WithMapping, WithHeadings
{
    public $data;
    public $request;

    public function __construct($data)
    {
        $this->data = $data;
        $this->request = json_decode($this->data->request, true);
    }

    public function query()
    {
        return Airdrop::query()
            ->where('type', $this->request['type'])
            ->when(!empty($this->request['keyword']), function ($q) {
                return $q->where(function ($q1) {
                    $likeVal = '%' . $this->request['keyword'] . '%';

                    return $q1->where('nickname', 'like', $likeVal)->orWhere('mobile', 'like', $likeVal)->orWhere('goods_name', 'like', $likeVal);
                });
            })
            ->when($this->request['status'], function ($q) {
                $status = $this->request['status'];
                if (3 == $this->request['status']) {
                    $status = 0;
                }

                return $q->where('status', $status);
            })
            ->when($this->request['start_date'], function ($q) {
                $q->whereDate('created_at', '>=', $this->request['start_date']);
            })
            ->when($this->request['end_date'], function ($q) {
                $q->whereDate('created_at', '<=', $this->request['end_date']);
            })
            ->where('agent_id', $this->data->agent_id)
            ->orderByDesc('id')
            ->limit(30000);
    }

    public function headings(): array
    {
        return [
            'ID',
            '商品id',
            '商品名称',
            '空投数量',
            '接收人',
            '手机号',
            '钱包地址',
            '订单状态',
            '原因',
            '下单时间',
        ];
    }

    public function map($value): array
    {
        if (1 == $value['status']) {
            $order_status = '成功';
        } elseif (2 == $value['status']) {
            $order_status = '失败';
        } else {
            $order_status = '空投中';
        }
        $value['nickname'] = drop_special_char($value['nickname']);

        return [
            $value['id'],
            $value['goods_id'],
            $value['goods_name'],
            $value['number'],
            $value['nickname'] ?? '',
            ' ' . $value['mobile'],
            ' ' . $value['qianbao'],
            $order_status,
            $value['error_msg'],
            $value['created_at'],
        ];
    }
}
